package com.mcptt.http.operator.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.json.JSONObject;

import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.product.log.Log;
import com.mcptt.comm.CommonFunc;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.http.operator.IHttpOpCb;
import com.mcptt.http.operator.OkHttpUtils;

import android.os.Handler;
import android.os.Message;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DownloadFileLoader implements Callback{
	protected final static int OP_SUC = 0;
	protected final static int OP_FAILED = 1;
	private static final String HTTP_KEY = "http://";;
	private static final String Sub_Url = ":8030/xpoc/ue-fse-downloadfd";
	private String svrIp = null;
	private String jsonStr = null;
	protected IHttpOpCb callback = null;
	private OnDownloadListener listener = null;

//	private String destFileDir = null;
	private  String destFileName = null;

	public DownloadFileLoader(String svrIp,String jsonStr,IHttpOpCb callback,OnDownloadListener listener)
	{
		this.svrIp = svrIp;
		this.jsonStr = jsonStr;
//		this.destFileDir = destFileDir;
		if(jsonStr != null)
		{
			try
			{
				if(jsonStr.contains("FileName"))
				{
					JSONObject obj = new JSONObject(jsonStr);
					this.destFileName = obj.get("FileName").toString();

				}
				else
				{
					this.destFileName = generateName();
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
				this.destFileName = generateName();
			}
		}
		else
		{
			this.destFileName = generateName();
		}
		Log.debug(getClass(), "doPostFile destFileName = " + destFileName);
		String destFileDir = FileOperation.getFilePath(SessionInfo.Filetype_File);
		//储存下载文件的目录
		File dir = new File(destFileDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, destFileName);
		if(file.exists())
		{
			file.delete();
		}
		
		
		this.callback = callback;
		this.listener = listener;
	}

	public void downLoad() {
		final String url = HTTP_KEY + svrIp + Sub_Url;
		new Thread(new Runnable(){
			@Override
			public void run() 
			{
				try {
					doDownloadFile(url,jsonStr);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void doDownloadFile(String url,String jsonStr) throws Exception
	{
		Log.debug(getClass(), "doPostFile url = " + url + " jsonStr = " + jsonStr);
		OkHttpUtils.getInstance().download(url, jsonStr,this);//.doPostFile(url, file, newFileName,this, listener);
	}



	private void sendOpResultMsg(boolean isSuc)
	{
		if(isSuc)
		{
			Message msg = handler.obtainMessage(OP_SUC);
			msg.sendToTarget();
		}
		else
		{
			Message msg = handler.obtainMessage(OP_FAILED);
			msg.sendToTarget();
		}
	}

	protected Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch(msg.what)
			{
			case OP_SUC:
				if(callback != null)
				{
					callback.onOpResult(IHttpOpCb.Id_DownLoad,true,0,"");
				}
				break;
			case OP_FAILED:
				if(callback != null)
				{
					callback.onOpResult(IHttpOpCb.Id_DownLoad,false,0,"");
				}
				break;
			}
		}
	};
	@Override
	public void onFailure(Call call, IOException e) {
		// 下载失败监听回调
		sendOpResultMsg(false);
	}

	@Override
	public void onResponse(Call call, Response response) throws IOException {

		InputStream is = null;
		byte[] buf = new byte[2048];
		int len = 0;
		FileOutputStream fos = null;
		String destFileDir = FileOperation.getFilePath(SessionInfo.Filetype_File);
		//储存下载文件的目录
		File dir = new File(destFileDir);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, destFileName);

		try {

			is = response.body().byteStream();
			long total = response.body().contentLength();
			fos = new FileOutputStream(file);
			long sum = 0;
			while ((len = is.read(buf)) != -1) {
				fos.write(buf, 0, len);
				sum += len;
				int progress = (int) (sum * 1.0f / total * 100);
				//下载中更新进度条
				if(listener != null)
				{
					String localPaht = destFileDir + destFileName;
					listener.onDownloading(progress,localPaht);
				}
			}
			fos.flush();
			//下载完成
			sendOpResultMsg(true);
		} catch (Exception e) 
		{
			e.printStackTrace();
			sendOpResultMsg(false);
		}finally {

			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {

			}

		}
	}
	
	private String generateName() {
		return CommonFunc.getDateAndTime2() + ".tmp";
	}
}
